import { Platform, AlertController, Config } from "ionic-angular";
import { Injectable } from "@angular/core";
import { Http, Headers, RequestOptions, Response } from "@angular/http";
import { appConfig } from "./config";
import { GlobalVars } from "./globalVars";
import * as moment from "moment";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import "rxjs/add/operator/retry";
import "rxjs/add/operator/timeout";
import "rxjs/add/operator/catch";
import "rxjs/add/observable/throw";
import { Storage } from "@ionic/storage";
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { FileOpener } from '@ionic-native/file-opener';
import { File } from '@ionic-native/file';

let headers = new Headers({
  "x-app": "1",
  "x-ajax": "1",
  "Content-Type": "application/json"
});
let options = new RequestOptions({ headers: headers });

let b = "VJzWZc%F";
@Injectable()
export class HttpService {
  token: string;
  constructor(
    private http: Http,
    private globalVars: GlobalVars,
    private storage: Storage,
    private platform: Platform,
    private transfer: FileTransfer,
    private file: File,
    private fileOpener: FileOpener,
    private alertCtrl: AlertController,
  ) {
    this.http = http;
  }

  post(url: string, params: Object, options: RequestOptions) {
    let headers = new Headers({
      "x-app": "1",
      "x-ajax": "1",
      "Content-Type": "application/json",
      Authorization: "Bearer " + this.globalVars.getMyGlobalVar("token")
    });
    let optionss = new RequestOptions({ headers: headers });
    if (params) {

      params = window['Base64'].encode((JSON.stringify(params)));
      params = this.base64Encode(params);
    }
    return this.http
      .post(url, params, optionss)
      .retry(appConfig.retryTimes)
      .timeout(appConfig.timeout)
      .map(this.extractData)
      .catch(this.handleError);
  }

  postLogin(url: string, params: Object, options: RequestOptions) {
    let headers = new Headers({
      "x-app": "1",
      "x-ajax": "1",
      "Content-Type": "application/json",
      Authorization: "Bearer " + this.globalVars.getMyGlobalVar("token")
    });
    let optionss = new RequestOptions({ headers: headers });
    if (params) {
      params = window['Base64'].encode((JSON.stringify(params)));
      params = this.base64Encode(params);
    }
    return this.http
      .post(url, params, optionss)
      .retry(appConfig.retryTimes)
      .timeout(4000)
      .map(this.extractData)
      .catch(this.handleError);
  }

  //参数加密
  /*base64Encode(parmas) {
    let aesUtil = window["AesUtil"];
    parmas.soc = new Date().getTime();
    if (parmas) {
      let encodeString = aesUtil.Encrypt(
        JSON.stringify(parmas),
        appConfig.a + b
      );
      let param = {
        securityParam: encodeString
      };
      return param;
    }
    return null;
  }*/

  base64Encode(parmas) {
    let aesUtil = window['AesUtil'];
    // parmas.soc = new Date().getTime();
    if (parmas) {
      let encodeString = aesUtil.Encrypt(parmas, appConfig.a + b);
      let param = {
        'securityParam': encodeString
      }
      return param;
    }
    return null;
  }

  /**
   * extractData: 接口返回成功数据处理
   */
  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  /**
   * handleError: 接口返回错误处理
   */
  private handleError(error) {
    return Observable.throw(error || "Server error");
  }

  /**
 * 是否真机环境
 * @return {boolean}
 */
  isMobile(): boolean {
    return this.platform.is('mobile') && !this.platform.is('mobileweb');
  }

  /**
   * 是否android真机环境
   * @return {boolean}
   */
  isAndroid(): boolean {
    return this.isMobile() && this.platform.is('android');
  }

  /**
   * 是否ios真机环境
   * @return {boolean}
   */
  isIos(): boolean {
    return this.isMobile() && (this.platform.is('ios') || this.platform.is('ipad') || this.platform.is('iphone'));
  }

  /**
* 下载安装app
*/
  downloadApp(url) {
    if (true) {
      let alert = this.alertCtrl.create({
        title: '下载进度：0%',
        enableBackdropDismiss: false,
        buttons: ['后台下载']
      });
      alert.present();

      const fileTransfer: FileTransferObject = this.transfer.create();
      this.file.createDir(this.file.externalRootDirectory, "appFolder", true).then(link => {
        const apk = this.file.externalRootDirectory + 'appFolder/elevator.apk'; //apk保存的目录

        fileTransfer.download(url, apk).then((entry) => {
          const nativePath = entry.toURL();
          this.fileOpener.open(nativePath, 'application/vnd.android.package-archive').then(
            () => {
            });
        });
      })


      fileTransfer.onProgress((event: ProgressEvent) => {
        let num = Math.floor(event.loaded / event.total * 100);
        if (num === 100) {
          alert.dismiss();
        } else {
          let title = document.getElementsByClassName('alert-title')[0];
          title && (title.innerHTML = '下载进度：' + num + '%');
        }
      });
    }
  }

  /**
   * 获取pc端菜单权限
   */
  getCurrentUserMenuInfo(params: Object) {
    //拼装pc的请求头
    let pcheaders = new Headers({
      "x-ajax": "1",
      "Content-Type": "application/x-www-form-urlencode"
    });
    let pcoptions = new RequestOptions({ headers: pcheaders });
    let url = appConfig.IP_URL + appConfig.API.getUserMenuInfo;
    return this.post(url, params, pcoptions);
  }

  /**
   * 获取版本号
   * @returns {Observable<Response>}
   */
  getVersion(param) {
    let url = appConfig.IP_URL + appConfig.API.getVersion;
    return this.post(url, param, options);
  }

  /**
   * login: 用户登录
   */
  login(params: Object) {
    let url = appConfig.IP_URL + appConfig.API.login;
    return this.postLogin(url, params, options);
  }

  /**
   * logout: 用户注销
   */
  logout(params: Object) {
    let url = appConfig.IP_URL + appConfig.API.logout;
    return this.post(url, params, options);
  }

  /**
   * getUserInfo: 获取登录用户信息
   */
  getUserInfo(params: Object) {
    let url = appConfig.IP_URL + appConfig.API.getUserInfo;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  /**
   * getUserInfo: 获取登录用户信息积分
   */
  getMarkById(params: Object) {
    let url = appConfig.IP_URL + appConfig.API.getMarkById;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  /**
   * getUserMenuInfo: 获取登录用户权限
   */
  getUserMenuInfo(params: Object) {
    let url = appConfig.IP_URL + appConfig.API.getUserMenuInfo;
    /*let par = this.base64Encode(params);*/
    return this.post(url, params, options);
  }

  /**
   * 获取通知查询
   * @param params
   */
  noticeQueryList(params: Object) {
    let url = appConfig.IP_URL + appConfig.API.noticeQueryList;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  /**
   * 获取资讯
   * @param params
   * @returns {Observable<R|T>}
   */
  informationQueryList(params: Object) {
    let url = appConfig.IP_URL + appConfig.API.informationQueryList;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  queryElevatorInfo(params) {
    let url = appConfig.IP_URL + appConfig.API.queryElevatorInfo + params.id;
    return this.post(url, params, options);
  }

  queryElevatorType(params) {
    let url = appConfig.IP_URL + appConfig.API.queryElevatorType;
    return this.post(url, params, options);
  }

  queryPartyById(params) {
    let url = appConfig.IP_URL + appConfig.API.queryPartyById + params.id;
    return this.post(url, params, options);
  }

  queryRepairList(params) {
    let url = appConfig.IP_URL + appConfig.API.queryRepairList;
    return this.post(url, params, options);
  }
  queryEmergencyList(params) {
    let url = appConfig.IP_URL + appConfig.API.queryEmergencyList;
    return this.post(url, params, options);
  }
  //获取通知的详情
  noticeFindById(params) {
    let url = appConfig.IP_URL + appConfig.API.noticeFindById;
    //let par = this.base64Encode(params);
    return this.post(url + params, null, options);
  }

  //获取咨询的详情
  informationById(params) {
    let url = appConfig.IP_URL + appConfig.API.informationById;
    //let par = this.base64Encode(params);
    return this.post(url + params, null, options);
  }

  queryDebris(params) {
    let url = appConfig.IP_URL + appConfig.API.queryDebris;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  queryEscalator(params) {
    let url = appConfig.IP_URL + appConfig.API.queryEscalator;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  queryHydpress(params) {
    let url = appConfig.IP_URL + appConfig.API.queryHydpress;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  queryTraction(params) {
    let url = appConfig.IP_URL + appConfig.API.queryTraction;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  //电梯添加
  addRepairInfoElevator(params) {
    let url = appConfig.IP_URL + appConfig.API.addRepairInfoElevator;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  addDebris(params) {
    let url = appConfig.IP_URL + appConfig.API.addDebris;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  addEscalator(params) {
    let url = appConfig.IP_URL + appConfig.API.addEscalator;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  addHydpress(params) {
    let url = appConfig.IP_URL + appConfig.API.addHydpress;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  addTraction(params) {
    let url = appConfig.IP_URL + appConfig.API.addTraction;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  //救援新增
  emergencyRescueAdd(params) {
    let url = appConfig.IP_URL + appConfig.API.emergencyRescueAdd;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  //救援演练
  rescueDrillAdd(params) {
    let url = appConfig.IP_URL + appConfig.API.rescueDrillAdd;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  //巡检
  inspectionAdd(params) {
    let url = appConfig.IP_URL + appConfig.API.inspectionAdd;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  /**
   * 用户设备号绑定
   */
  handleUserRegId(params) {
    let url = appConfig.IP_URL + appConfig.API.handleUserRegId;
    return this.post(url, params, options);
  }

  queryUsedRepairList(params) {
    let url = appConfig.IP_URL + appConfig.API.queryUsedRepairList;
    return this.post(url, params, options);
  }

  updateRepairList(params) {
    let url = appConfig.IP_URL + appConfig.API.updateRepairInfo;
    return this.post(url, params, options);
  }

  queryRepairInfoById(params) {
    let url = appConfig.IP_URL + appConfig.API.queryRepairInfoById;
    return this.post(url, params, options);
  }
  //更新通知
  updateReadState(params) {
    let url = appConfig.IP_URL + appConfig.API.updateReadState;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  addAppliyRepair(params) {
    let url = appConfig.IP_URL + appConfig.API.addAppliyRepair;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  queryAppliyRepair(param) {
    let url = appConfig.IP_URL + appConfig.API.queryAppliyRepair;
    //let par = this.base64Encode(params);
    return this.post(url + param, null, options);
  }

  updateRepairApply(params) {
    let url = appConfig.IP_URL + appConfig.API.updateRepairApply;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  getRepairApplyList(params) {
    let url = appConfig.IP_URL + appConfig.API.getRepairApplyList;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }
  addEleUsedInspect(params) {
    let url = appConfig.IP_URL + appConfig.API.addEleUsedInspect;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }
  addUsedControl(params) {
    let url = appConfig.IP_URL + appConfig.API.addUsedControl;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  queryByIdAndTypeList(params) {
    let url = appConfig.IP_URL + appConfig.API.queryByIdAndTypeList;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }
  addSafeControlRecord(params) {
    let url = appConfig.IP_URL + appConfig.API.addSafeControlRecord;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  getSafeConById(param) {
    let url = appConfig.IP_URL + appConfig.API.getSafeConById;
    //let par = this.base64Encode(params);
    return this.post(url + param, null, options);
  }

  updateSafeContr(params) {
    let url = appConfig.IP_URL + appConfig.API.updateSafeContr;
    //let par = this.base64Encode(params);
    return this.post(url, params, options);
  }

  queryUsedControlInspect(param) {
    let url = appConfig.IP_URL + appConfig.API.queryUsedControlInspect;
    //let par = this.base64Encode(params);
    return this.post(url + param, null, options);
  }

  queryelevatorUsed(param) {
    let url = appConfig.IP_URL + appConfig.API.queryelevatorUsed;
    //let par = this.base64Encode(params);
    return this.post(url + param, null, options);
  }
  advertiseQuery(param) {
    let url = appConfig.IP_URL + appConfig.API.advertiseQuery;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  queryTractionDetails(param) {
    let url = appConfig.IP_URL + appConfig.API.queryTractionDetails;
    //let par = this.base64Encode(params);
    return this.post(url + param, null, options);
  }

  queryDebrisDetails(param) {
    let url = appConfig.IP_URL + appConfig.API.queryDebrisDetails;
    //let par = this.base64Encode(params);
    return this.post(url + param, null, options);
  }

  queryEscalatorDetails(param) {
    let url = appConfig.IP_URL + appConfig.API.queryEscalatorDetails;
    //let par = this.base64Encode(params);
    return this.post(url + param, null, options);
  }

  queryHydpressDetails(param) {
    let url = appConfig.IP_URL + appConfig.API.queryHydpressDetails;
    //let par = this.base64Encode(params);
    return this.post(url + param, null, options);
  }

  queryPartyByNameLk(param) {
    let url = appConfig.IP_URL + appConfig.API.queryPartyByNameLk;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  addSelfCheckRecord(param) {
    let url = appConfig.IP_URL + appConfig.API.addSelfCheckRecord;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  updateLatLng(param) {
    let url = appConfig.IP_URL + appConfig.API.updateLatLng;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  queryPlanDetail(param) {
    let url = appConfig.IP_URL + appConfig.API.queryPlanDetail;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  queryPlanDictItem(param) {
    let url = appConfig.IP_URL + appConfig.API.queryPlanDictItem1;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  queryPlanDictItem1(param) {
    let url = appConfig.IP_URL + appConfig.API.queryPlanDictItem1;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  updateSafeContrCheck(param) {
    let url = appConfig.IP_URL + appConfig.API.updateSafeContrCheck;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  queryCheckResult(param) {
    let url = appConfig.IP_URL + appConfig.API.queryCheckResult;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  queryEmpiric(param) {
    let url = appConfig.IP_URL + appConfig.API.queryEmpiric;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }


  updateUserPwd(param) {
    let url = appConfig.IP_URL + appConfig.API.updateUserPwd;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  updateUserPhone(param) {
    let url = appConfig.IP_URL + appConfig.API.updateUserPhone;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  addByRead(param) {
    let url = appConfig.IP_URL + appConfig.API.addByRead;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  getUserList(param) {
    let url = appConfig.IP_URL + appConfig.API.getUserList;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  getInspectionList(param) {
    let url = appConfig.IP_URL + appConfig.API.getInspectionList;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  updateUserFace(param) {
    let url = appConfig.IP_URL + appConfig.API.updateUserFace;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }
  addActivity1(param) {
    let url = appConfig.IP_URL + appConfig.API.addActivity1;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  addMeatasis(param) {
    let url = appConfig.IP_URL + appConfig.API.addMeatasis;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  updateElevatorPlace(param) {
    let url = appConfig.IP_URL + appConfig.API.updateElevatorPlace;
    //let par = this.base64Encode(params);
    return this.post(url, param, options);
  }

  queryLaws(param) {
    let url = appConfig.IP_URL + appConfig.API.queryLaws;
    return this.post(url, param, options);
  }

  queryCheckUser(param) {
    let url = appConfig.IP_URL + appConfig.API.queryCheckUser;
    return this.post(url + param, param, options);
  }

  // 获取未完成维保记录
  queryMaintRecord(param) {
    let url = appConfig.IP_URL + appConfig.API.queryMaintRecord;
    return this.post(url, param, options);
  }

  // 维保获取检查项
  findCheckItemApp(param) {
    let url = appConfig.IP_URL + appConfig.API.findCheckItemApp;
    return this.post(url, param, options);
  }

  // 维保获取电梯信息
  findElevatorInfo(param) {
    let url = appConfig.IP_URL + appConfig.API.findElevatorInfo;
    return this.post(url, param, options);
  }

  // 新增维保检查项
  addCheckItemApp(param) {
    let url = appConfig.IP_URL + appConfig.API.addCheckItemApp;
    return this.post(url, param, options);
  }
  // 获取完成维保记录
  queryFinishRecord(param) {
    let url = appConfig.IP_URL + appConfig.API.queryFinishRecord;
    return this.post(url, param, options);
  }

  getFileType(fileName: string) {
    return fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
  }

  //查询96333 电梯信息
  findElevatorInfoBy96333(param) {
    let url = appConfig.IP_URL + appConfig.API.getEleInfoBy96333Code;
    return this.post(url, param, options);
  }

  getElevatorInfoByNum(param) {
    let url = appConfig.IP_URL + appConfig.API.getElevatorInfoByNum;
    return this.post(url, param, options);
  }

  // 多台电梯的缓存数据
  querySpotCheckCacheApp(param) {
    let url = appConfig.IP_URL + appConfig.API.querySpotCheckCacheApp;
    return this.post(url, param, options);
  }


  queryCheckItem(param) {
    let url = appConfig.IP_URL + appConfig.API.queryCheckItem;
    return this.post(url, param, options);
  }

  // 初始化电梯故障
  initfault(param) {
    let url = appConfig.IP_URL + appConfig.API.initfault;
    return this.post(url, param, options);
  }



  getFileMimeType(fileType: string) {
    let mimeType: string = '';

    switch (fileType) {
      case 'txt':
        mimeType = 'text/plain';
        break;
      case 'docx':
        mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        break;
      case 'doc':
        mimeType = 'application/msword';
        break;
      case 'pptx':
        mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        break;
      case 'ppt':
        mimeType = 'application/vnd.ms-powerpoint';
        break;
      case 'xlsx':
        mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        break;
      case 'xls':
        mimeType = 'application/vnd.ms-excel';
        break;
      case 'zip':
        mimeType = 'application/x-zip-compressed';
        break;
      case 'rar':
        mimeType = 'application/octet-stream';
        break;
      case 'pdf':
        mimeType = 'application/pdf';
        break;
      case 'jpg':
        mimeType = 'image/jpeg';
        break;
      case 'png':
        mimeType = 'image/png';
        break;
      default:
        mimeType = 'application/' + fileType;
        break;
    }
    return mimeType;
  }

}
